﻿using DocTranslator.Hubs;
using DocTranslator.Models;
using DocTranslator.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;

namespace DocTranslator.Controllers
{
    public class TranslationController : Controller
    {
        private readonly ITranslationService _translationService;
        private readonly IWordDocumentService _wordDocumentService;
        private readonly IHubContext<TranslationHub> _hubContext;
        private readonly ILogger<TranslationController> _logger;

        public TranslationController(
            ITranslationService translationService,
            IWordDocumentService wordDocumentService,
            IHubContext<TranslationHub> hubContext,
            ILogger<TranslationController> logger)
        {
            _translationService = translationService;
            _wordDocumentService = wordDocumentService;
            _hubContext = hubContext;
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UploadDocuments(List<IFormFile> file, string connectionId)
        {
            if (file == null || file.Count == 0)
                return Json(new { success = false, message = "没有选择文件" });

            if (string.IsNullOrEmpty(connectionId))
                return Json(new { success = false, message = "连接ID不能为空" });

            var uploadedFiles = new List<string>();

            // 每次上传生成新的文件夹
            var folderId = "FileTranslator_" + Guid.NewGuid().ToString("N");
            var baseDir = Path.Combine(Directory.GetCurrentDirectory(), "App_Data", folderId);

            var uploadDirectory = Path.Combine(baseDir, "Upload");
            var downloadDirectory = Path.Combine(baseDir, "Down");

            Directory.CreateDirectory(uploadDirectory);
            Directory.CreateDirectory(downloadDirectory);


            foreach (var item in file)
            {
                if (item.Length > 0)
                {
                    // 验证文件类型
                    var extension = Path.GetExtension(item.FileName).ToLower();
                    if (extension != ".docx")
                    {
                        _logger.LogWarning($"不支持的文件类型: {item.FileName}");
                        continue;
                    }

                    // 检查文件大小限制
                    if (item.Length > 10 * 1024 * 1024) // 10MB
                    {
                        _logger.LogWarning($"文件过大: {item.FileName} ({item.Length} bytes)");
                        continue;
                    }

                    var filePath = Path.Combine(uploadDirectory, item.FileName);

                    // 保存传过来的文件
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await item.CopyToAsync(stream);
                    }

                    uploadedFiles.Add(filePath);
                    _logger.LogInformation($"文件已上传: {filePath}");
                }
            }

            if (uploadedFiles.Count == 0)
                return Json(new { success = false, message = "没有有效的Word文档" });

            // 在 HttpContext 还活着时生成 baseUrl
            string baseDownloadUrl = Url.Action("Download", "Translation", null, Request.Scheme);

            // 启动后台任务处理文档翻译
            _ = Task.Run(async () =>
            {
                try
                {
                    var resultFiles = await _wordDocumentService.ProcessDocumentsAsync(
                        uploadedFiles,
                        _translationService,
                        async (filecompleted, filetotal, grandcompleted, grandtotal, status) =>
                        {
                            await _hubContext.Clients.Client(connectionId).SendAsync(
                                "UpdateProgress",
                                filecompleted,
                                filetotal,
                                grandcompleted,
                                grandtotal,
                                status);
                        },
                        downloadDirectory
                        );

                    // 拼接下载链接，不再依赖 Url.Action
                    var downloadUrls = resultFiles.Select(f =>
                        $"{baseDownloadUrl}?folderId={folderId}&fileName={Uri.EscapeDataString(Path.GetFileName(f))}"
                    ).ToList();

                    // 通知前端翻译完成
                    await _hubContext.Clients.Client(connectionId).SendAsync(
                        "TranslationComplete",
                        downloadUrls);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "文档处理失败");
                    await _hubContext.Clients.Client(connectionId).SendAsync("TranslationError", ex.Message);
                }
            });

            return Json(new { success = true, message = "文件上传成功，开始处理" });
        }

        [HttpGet]
        public IActionResult Download(string folderId, string fileName)
        {
            if (string.IsNullOrEmpty(folderId) || string.IsNullOrEmpty(fileName))
                return BadRequest("参数缺失");

            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "App_Data", folderId, "Down", fileName);

            if (!System.IO.File.Exists(filePath))
                return NotFound();

            var memory = new MemoryStream();
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;

            return File(memory,
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                fileName);
        }


        [HttpGet]
        public IActionResult GetTranslatedFiles()
        {
            var uploadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "App_Data", "Uploads");
            if (!Directory.Exists(uploadDirectory))
                return Json(new List<string>());

            var files = Directory.GetFiles(uploadDirectory, "*_translated*")
                .Select(f => new {
                    Name = Path.GetFileName(f),
                    Url = Url.Action("Download", "Translation", new { fileName = Path.GetFileName(f) })
                })
                .ToList();

            return Json(files);
        }
    }
}

